package com.cjstudio.bluetermtest;

import com.cjstudio.feetgesture.BusinessFunction;
import com.cjstudio.feetgesture.GestureUtils;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


public abstract class GestureService {

	protected Context mContext;
	protected Handler mHandler;
    
	public GestureService(Context mContext, Handler mHandler) {
		this.mContext = mContext;
		this.mHandler = mHandler;
	}
	
	GestureRecognitionTask _GestureRecognitionTask;
	
	public void startGestureService() {
		Log.e("NRT", "startGestureService");
		if(_GestureRecognitionTask == null) {
			_GestureRecognitionTask = new GestureRecognitionTask(mContext, mHandler);
		}
		_GestureRecognitionTask.execute(mContext);
	}
	
	public void stopGestureService() {
		if(_GestureRecognitionTask != null) {
			_GestureRecognitionTask.cancel(true);
		}
	}
	
	protected Queue __Queue;
	
	public int __action;
	public int DETECTION_FREQUENCY = 400;
	
	public abstract void pre();
	public abstract void post();
	
	protected class GestureRecognitionTask extends AsyncTask<Context, Integer, Integer> {
		
		Context mContext;
		Handler mHandler;
		
		public GestureRecognitionTask(Context mContext, Handler mHandler) {
			this.mContext = mContext;
			this.mHandler = mHandler;
		}
		
		protected Integer doInBackground(Context... params) {
			try {		
				while(true) {
					pre();
					
					if(__Queue != null) {
						__action = BusinessFunction.recognize(__Queue.xVals, __Queue.yVals, __Queue.zVals, __Queue.WINDOW_SIZE);
						if(__action != 0 && __action != BusinessFunction.ACTION_3) {
							Log.e("Feet", GestureUtils.strAction(__action));
							
							 // Send a failure message back to the Activity
					        Message msg = mHandler.obtainMessage(BlueTerm.MESSAGE_ACTION);
					        Bundle bundle = new Bundle();
					        bundle.putString(BlueTerm.TOAST, GestureUtils.strAction(__action));
					        msg.setData(bundle);
					        mHandler.sendMessage(msg);
					        
//							Toast.makeText(mContext, GestureUtils.strAction(__action), Toast.LENGTH_SHORT).show();
						}
					}
					post();
					
					Thread.sleep(DETECTION_FREQUENCY);
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		
		protected void onPreExecute() { }
		protected void onProgressUpdate(Integer... values) { }
		protected void onCancelled() { }
		protected void onPostExecute(Integer result) { }
	}
}
